#include "functions.h"
#include "trie.h"

int main(int argc, char *argv[]) {

	trie *words = trie_new();
	char *token, *rest, *ptr;
	char fname[30];

	int fsizevar;
	int total;
	time_t start;

	char *fcontent;
	FILE *f;

	strcpy(fname, (argc > 1 && argv[1] != NULL) ? argv[1] : FILE_NAME);

	fsizevar = fsize(fname);
	fcontent = (char*) calloc(fsizevar, sizeof(char));

	// Abre o arquivo
	if(!(f = fopen(fname, "r")) || !fread(fcontent, sizeof(char), fsizevar, f)) {
		printf("ERRO: Erro ao ler o arquivo.\n");
		exit(1);
	}
	fclose(f);

	ptr = fcontent;
	// Organiza as palavras em uma lista encadeada de palavras
	while((token = strtok_r(ptr, "1234567890'$ ,.-()\n\r", &rest))) {
		split_word(words, token);
		ptr = rest;
	}

	total = trie_num_entries(words);
	printf("Total de Palavras %d\n", total);
	
	srand(time(NULL));
	start = time(NULL);

	while(check_entries(trie_num_entries(words), total, start))
		remove_words(words);

	printf("TERMINOU!\n");

	trie_delete(words);

  return 0;
}
